//koa  中间件：async await  app.use()
const qs = require('querystring');
function getParams(ctx){
    //promise  容器
    return new Promise((resolve,reject) => {
        let str = '';
        ctx.req.on('data',(chunk) => {
            str += chunk;
        })

        ctx.req.on('end',() => {
            console.log("str",str); //username=%E6%9D%8E%E6%99%93%E4%B8%B9 & age=20&address=%E6%B2%B3%E5%8C%97
            //前端传递参数的类型：'application/x-www-form-urlencoded'   'application/json' 
            if(ctx.header['content-type'] === 'application/x-www-form-urlencoded'){
                resolve(qs.parse(str));
            }else{
                resolve(JSON.parse(str));
            }
        })
    })
}

module.exports = () => {
    return async (ctx,next) => {
        console.log(ctx.method);
        if(ctx.method === 'POST' || ctx.method === 'PUT'){
            //处理  post  put
            ctx.request.body = await getParams(ctx);
            await next()
        }else{
            await next(); //执行下一个中间件
        }
    }
}